package cn.wolfcode.rbac.sercurity.service;

import cn.wolfcode.rbac.common.Constants;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.sercurity.domian.LoginUser;
import cn.wolfcode.rbac.utils.IdUtils;
import cn.wolfcode.rbac.utils.JsonUtils;
import cn.wolfcode.rbac.utils.RedisUtils;
import cn.wolfcode.rbac.utils.SpringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenService {
    @Value("${token.secret}")
    private String secret;
    @Value("${token.header}")
    private String header;
    // 1.创建Token
    public String createToken(LoginUser loginUser) {
        Map<String, Object> claims = new HashMap<>();
        String uuid = IdUtils.fastUUID();
        loginUser.setUuid(uuid);
        claims.put(Constants.LOGIN_EMPLOYEE,uuid);
        return Jwts.builder().signWith(SignatureAlgorithm.HS512, secret).addClaims(claims).compact();
    }

    // 2.根据请求头里面的Token，校验Token，获取用户信息
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求头内容
        String token = request.getHeader(this.header);
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        // 检验token 获取用户信息
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        String uuid = (String) claims.get(Constants.LOGIN_EMPLOYEE);
        // 构建LoginUser
        RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
        Employee employee = (Employee) JsonUtils.fromJson(redisUtils.get(Constants.LOGIN_EMPLOYEE + uuid), Employee.class);
        LoginUser loginUser = new LoginUser(employee,uuid);
        return loginUser;
    }
}
